import React, { useState } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Tree,
  message,
  Select,
  Divider,
} from "antd";
import { EditOutlined } from "@ant-design/icons";
import type { DataNode } from "antd/es/tree";

interface Role {
  id: number;
  name: string;
  code: string;
  permissions: string[];
}

const RolePermission: React.FC = () => {
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [roles, setRoles] = useState<Role[]>([
    {
      id: 1,
      name: "超级管理员",
      code: "SUPER_ADMIN",
      permissions: ["*"],
    },
    {
      id: 2,
      name: "普通用户",
      code: "USER",
      permissions: ["view:profile", "edit:profile"],
    },
  ]);

  // 权限树数据
  const permissionTree: DataNode[] = [
    {
      title: "系统管理",
      key: "system",
      children: [
        {
          title: "用户管理",
          key: "user",
          children: [
            { title: "查看用户", key: "view:user" },
            { title: "创建用户", key: "create:user" },
            { title: "编辑用户", key: "edit:user" },
            { title: "删除用户", key: "delete:user" },
          ],
        },
        {
          title: "角色管理",
          key: "role",
          children: [
            { title: "查看角色", key: "view:role" },
            { title: "创建角色", key: "create:role" },
            { title: "编辑角色", key: "edit:role" },
            { title: "删除角色", key: "delete:role" },
          ],
        },
        {
          title: "权限管理",
          key: "permission",
          children: [
            { title: "查看权限", key: "view:permission" },
            { title: "分配权限", key: "assign:permission" },
          ],
        },
      ],
    },
    {
      title: "个人中心",
      key: "profile",
      children: [
        { title: "查看个人信息", key: "view:profile" },
        { title: "编辑个人信息", key: "edit:profile" },
      ],
    },
    {
      title: "系统设置",
      key: "settings",
      children: [
        { title: "查看设置", key: "view:settings" },
        { title: "修改设置", key: "edit:settings" },
      ],
    },
  ];

  const columns = [
    {
      title: "角色名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "角色编码",
      dataIndex: "code",
      key: "code",
    },
    {
      title: "权限数量",
      key: "permissionCount",
      render: (record: Role) => record.permissions.length,
    },
    {
      title: "操作",
      key: "action",
      render: (_: unknown, record: Role) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            配置权限
          </Button>
        </Space>
      ),
    },
  ];

  // 获取所有权限的叶子节点
  const getAllPermissionKeys = (tree: DataNode[]): string[] => {
    const keys: string[] = [];
    const traverse = (nodes: DataNode[]) => {
      nodes.forEach((node) => {
        if (node.children) {
          traverse(node.children);
        } else {
          keys.push(node.key as string);
        }
      });
    };
    traverse(tree);
    return keys;
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    const allPermissions = getAllPermissionKeys(permissionTree);
    form.setFieldsValue({
      roleId: role.id,
      permissions: role.permissions.includes("*")
        ? allPermissions
        : role.permissions,
    });
    setModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then((values) => {
      if (editingRole) {
        // 更新角色权限
        setRoles(
          roles.map((role) =>
            role.id === editingRole.id
              ? { ...role, permissions: values.permissions }
              : role
          )
        );
        message.success("权限配置更新成功");
        setModalVisible(false);
      }
    });
  };

  return (
    <Card title="角色权限配置">
      <Table columns={columns} dataSource={roles} rowKey="id" />
      <Modal
        title="配置角色权限"
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="roleId" label="角色">
            <Select disabled>
              {roles.map((role) => (
                <Select.Option key={role.id} value={role.id}>
                  {role.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Divider />
          <Form.Item name="permissions" label="权限配置">
            <Tree
              checkable
              defaultExpandAll
              treeData={permissionTree}
              fieldNames={{
                title: "title",
                key: "key",
                children: "children",
              }}
            />
          </Form.Item>
          <div style={{ marginTop: 16 }}>
            <Button
              type="link"
              onClick={() => {
                form.setFieldsValue({
                  permissions: getAllPermissionKeys(permissionTree),
                });
              }}
            >
              全选
            </Button>
            <Button
              type="link"
              onClick={() => {
                form.setFieldsValue({ permissions: [] });
              }}
            >
              清空
            </Button>
          </div>
        </Form>
      </Modal>
    </Card>
  );
};

export default RolePermission;
